package vn.com.vega.chacha.v2;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import vn.com.vega.chacha.R;
import vn.com.vega.chacha.v2.AlbumDetail.ISelectSongPlay;
import vn.com.vega.chacha.v2.receiver.NetworkStatusReceiver;
import vn.com.vega.music.clientserver.JsonSong;
import vn.com.vega.music.objects.Playlist;
import vn.com.vega.music.objects.Song;
import vn.com.vega.music.utils.PlaylistUtil;
import vn.com.vega.music.utils.PlaylistUtil.SharePlaylistListener;
import vn.com.vega.music.utils.PlaylistUtil.likeAndUnlikePlaylistListener;
import vn.com.vega.music.utils.Util;
import vn.com.vega.music.view.adapter.AlbumdetailAdapter;
import vn.com.vega.music.view.adapter.MixAdapter;
import vn.com.vega.music.view.adapter.PlaylistDetailAdapter;
import vn.com.vega.music.view.adapter.SongListAdapter;
import vn.com.vega.music.view.custom.BottomPlayerView;
import vn.com.vega.music.view.custom.BottomPlayerView.ShowHideBottomPlayerListener;
import vn.com.vega.music.view.custom.LoadingView;
import vn.com.vega.music.view.custom.LoadingView.RetryListener;
import vn.com.vega.music.view.custom.TopTaskbarView;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class PlaylistDetail extends ActivityBase implements OnClickListener {
	// public static final String INDEX_KEY = "index of playlist";
	public static final String KEY_PLAYLIST_NAME = "Name of playlist";
	private static final String TAG_MENU_LIKE_PLAYLIST = "menu like playlist";
	private static final String TAG_MENU_SHARE_PLAYLI_STRING = "menu share playlist";

	private ListView playlistDetail;
	private MixAdapter adapter;
	private PlaylistDetailAdapter playlistDetailAdapter;
	private SongListAdapter songListAdapter;
	private View pinView;
	private TextView playAll;
	private TextView selectSongPlay;
	private LoadingView loadingData;
	private Playlist mPlaylist;
	private LoadingListSongForPlaylist loadingListSong;
	private Appinstant mApp;
	private TopTaskbarView mTopTaskbarView;
	private BottomPlayerView mBottomPlayerView;
	private View mViewReplacePlayer;
	private ISelectSongPlay selectSongPlayInterface;

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.album_detail);
		mApp = (Appinstant) getApplication();
		mTopTaskbarView = (TopTaskbarView) findViewById(R.id.topTaskbarView_album_detail);

		playlistDetail = (ListView) findViewById(R.id.lv_album_detail);
		pinView = findViewById(R.id.pinview_album_detail);
		pinView.setVisibility(View.GONE);
		playAll = (TextView) findViewById(R.id.tv_play_all_song);
		selectSongPlay = (TextView) findViewById(R.id.tv_select_song_play);
		playAll.setOnClickListener(this);
		selectSongPlay.setOnClickListener(this);
		playlistDetail = (ListView) findViewById(R.id.lv_album_detail);
		loadingData = (LoadingView) findViewById(R.id.loadingView_loading_album);
		loadingData.setRetryListener(retryListener);
		loadingData.setVisibility(View.GONE);
		mBottomPlayerView = (BottomPlayerView) findViewById(R.id.bottomPlayerView_album_detail);
		mViewReplacePlayer = findViewById(R.id.view_replace_bottom_player);
		mBottomPlayerView.setShowHideListener(showHideBottomPlayerListener);

		// int playlistIndex = getIntent().getIntExtra(INDEX_KEY, -1);
		// if (playlistIndex != -1) {
		// Appinstant app = (Appinstant) getApplication();
		// mPlaylist = (Playlist) app.listPlaylistFeature.get(playlistIndex);
		// }
		init();
		initTopTaskBar();

	}

	private void initTopTaskBar() {
		mTopTaskbarView.showBackButton();
		mTopTaskbarView.showMainMenu(false);
		mTopTaskbarView.addExtractMenu(R.drawable.bt_menu_like_toptask_menu,
				likeClickListener, TAG_MENU_LIKE_PLAYLIST);
		mTopTaskbarView.addExtractMenu(R.drawable.bt_toptask_menu_share,
				shareClickListener, TAG_MENU_SHARE_PLAYLI_STRING);
		if (mPlaylist.isFavorite) {
			mTopTaskbarView.getExtractMenu(TAG_MENU_LIKE_PLAYLIST).setSelected(true);
		} else {
			mTopTaskbarView.getExtractMenu(TAG_MENU_LIKE_PLAYLIST).setSelected(false);
		}
	}

	View.OnClickListener likeClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			// TODO: check playlist is like or unlike here
			if (mPlaylist.isFavorite) {
				PlaylistUtil.doUnLikePlaylist(PlaylistDetail.this, mPlaylist,
						likeAndUnlikePlaylistListener);
			} else {
				PlaylistUtil.doLikePlaylist(PlaylistDetail.this, mPlaylist,
						likeAndUnlikePlaylistListener);
			}
		}
	};

	View.OnClickListener shareClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			PlaylistUtil.sharePlaylist(mPlaylist, PlaylistDetail.this,
					sharePlaylistListener);
		}
	};

	private SharePlaylistListener sharePlaylistListener = new SharePlaylistListener() {

		@Override
		public void shareSuccess(Playlist playlist) {
			// TODO Auto-generated method stub
			showToast("Chia sẻ playlist " + playlist.title + " thành công");
		}

		@Override
		public void shareFail(Playlist plalist, String errorMessage) {
			// TODO Auto-generated method stub
			if (Util.checkStringIsemptyOrNull(errorMessage)) {
				showToast("Chia sẻ playlist " + plalist.title + " thất bại");
			} else {
				showToast(errorMessage);
			}

		}
	};

	private likeAndUnlikePlaylistListener likeAndUnlikePlaylistListener = new likeAndUnlikePlaylistListener() {

		@Override
		public void unlikeSuccess() {
			// TODO Auto-generated method stub
			showToast("Xóa thành công playlist" + mPlaylist.title
					+ " khỏi danh sách playlist yêu thích");
			View menuLikeView = mTopTaskbarView
					.getExtractMenu(TAG_MENU_LIKE_PLAYLIST);
			menuLikeView.setSelected(false);
		}

		@Override
		public void unlikeFail(String msg) {
			// TODO Auto-generated method stub
			if (Util.checkStringIsemptyOrNull(msg)) {
				showToast("Xóa thất bại playlist " + mPlaylist.title
						+ " khỏi danh sách playlist yêu thích");
			} else {
				showToast(msg);
			}

			View menuLikeView = mTopTaskbarView
					.getExtractMenu(TAG_MENU_LIKE_PLAYLIST);
			menuLikeView.setSelected(true);
		}

		@Override
		public void startDoUnlike() {
			// TODO Auto-generated method stub
			showToast("Đang bỏ playlist " + mPlaylist.title
					+ " ra khỏi danh sách yêu thích");
		}

		@Override
		public void startDoLike() {
			// TODO Auto-generated method stub
			showToast("Đang thêm playlist" + mPlaylist.title
					+ " vào danh sách yêu thích");
		}

		@Override
		public void likeSuccess() {
			// TODO Auto-generated method stub
			showToast("Thêm thành công " + mPlaylist.title
					+ " vào danh sách playlist yêu thích");
			View menuLikeView = mTopTaskbarView
					.getExtractMenu(TAG_MENU_LIKE_PLAYLIST);
			menuLikeView.setSelected(true);
		}

		@Override
		public void likeFail(String msg) {
			// TODO Auto-generated method stub
			if (Util.checkStringIsemptyOrNull(msg)) {
				showToast("Thất bại khi thêm playlist " + mPlaylist.title
						+ " vào danh sách playlist yêu thích");
			} else {
				showToast(msg);
			}

			View menuLikeView = mTopTaskbarView
					.getExtractMenu(TAG_MENU_LIKE_PLAYLIST);
			menuLikeView.setSelected(false);
		}
	};

	ShowHideBottomPlayerListener showHideBottomPlayerListener = new ShowHideBottomPlayerListener() {

		@Override
		public void onShowBottomPlayer() {
			// TODO Auto-generated method stub
			mViewReplacePlayer.setVisibility(View.VISIBLE);
		}

		@Override
		public void onHideBottomPlayer() {
			// TODO Auto-generated method stub
			mViewReplacePlayer.setVisibility(View.GONE);
		}
	};

	private void init() {
		String playlistName = getIntent().getStringExtra(KEY_PLAYLIST_NAME);
		if (Util.checkStringIsemptyOrNull(playlistName)) {
			finish();
			return;
		}
		mPlaylist = mApp.tranportPlaylist.remove(playlistName);
		if (mPlaylist == null) {
			finish();
			return;
		}
		if (mPlaylist.songList == null || mPlaylist.songList.size() == 0) {
			loadListSong();
		} else {
			showPlaylistDetail();
		}
	}

	OnScrollListener onScrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			if (firstVisibleItem >= AlbumdetailAdapter.HEADER_TYPE) {
				pinView.setVisibility(View.VISIBLE);
			} else {
				pinView.setVisibility(View.GONE);
			}
		}
	};

	RetryListener retryListener = new RetryListener() {

		@Override
		public void onRetry() {
			// TODO Auto-generated method stub
			loadListSong();
		}
	};

	private void showPlaylistDetail() {
		playlistDetailAdapter = new PlaylistDetailAdapter(this, mPlaylist);
		List<Object> listSong = new ArrayList<Object>();
		listSong.addAll(mPlaylist.getSongList());
		songListAdapter = new SongListAdapter(this, listSong, false,
				PlaylistDetail.class.getName());
		List<BaseAdapter> listAdapter = new ArrayList<BaseAdapter>();
		listAdapter.add(playlistDetailAdapter);
		listAdapter.add(songListAdapter);
		adapter = new MixAdapter(listAdapter);
		playlistDetail.setAdapter(adapter);
		playlistDetail.setOnScrollListener(onScrollListener);

		selectSongPlayInterface = new ISelectSongPlay() {

			@Override
			public void selectSongPlay() {
				// TODO Auto-generated method stub
				if (songListAdapter != null && songListAdapter.getCount() > 0) {
//					mApp.tranportString.put(SelecSongPlay.KEY_LIST_SONG_TITLE,
//							mPlaylist.title);
					songListAdapter.selectSongPlay("Playlist: " + mPlaylist.title);
				}
			}

			@Override
			public void playAllSong() {
				// TODO Auto-generated method stub
				if (songListAdapter != null && songListAdapter.getCount() > 0) {
					songListAdapter.playAllSong("Playlist: " + mPlaylist.title);
				}
			}
		};
		playlistDetailAdapter
				.setSelectSongPlayInterface(selectSongPlayInterface);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (loadingListSong != null) {
			loadingListSong.cancel(true);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		mBottomPlayerView.stopUpdate();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mBottomPlayerView.startUpdate();
	}

	private void loadListSong() {
		loadingData.startLoading();
		if (loadingListSong != null
				&& loadingListSong.getStatus() == Status.RUNNING) {
			return;
		}
		if (loadingListSong != null
				&& loadingListSong.getStatus() != Status.RUNNING) {
			loadingListSong.cancel(true);
		}
		loadingListSong = new LoadingListSongForPlaylist(this);
		loadingListSong.execute();
	}

	static class LoadingListSongForPlaylist extends AsyncTask<Void, Void, Void> {
		WeakReference<PlaylistDetail> playlistDetailRfc;
		private ArrayList<Song> listSong;

		public LoadingListSongForPlaylist(PlaylistDetail albumDetail) {
			playlistDetailRfc = new WeakReference<PlaylistDetail>(albumDetail);
			listSong = new ArrayList<Song>();
		}

		private boolean checkAppIsLive() {
			PlaylistDetail albumDetail = playlistDetailRfc.get();
			if (albumDetail == null || albumDetail.isDestroy) {
				return false;
			}
			return true;
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			if (!checkAppIsLive()) {
				return null;
			}
			PlaylistDetail playlistDetail = playlistDetailRfc.get();
			if (NetworkStatusReceiver.isConnected()) {
				JsonSong jos = JsonSong
						.loadSongListByPlaylistId(playlistDetail.mPlaylist.serverId);

				if (jos.isSuccess()) {
					listSong.addAll(jos.songs);
				} else {
					Log.e(PlaylistDetail.class.getSimpleName(),
							jos.getErrorMessage());
					// message = jos.getErrorMessage();
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			if (isCancelled() || !checkAppIsLive()) {
				return;
			}
			final PlaylistDetail playlistDetail = playlistDetailRfc.get();
			if (listSong == null || listSong.size() == 0) {
				playlistDetail.loadingData.loadingFinish(false, null);
				playlistDetail.selectSongPlayInterface = null;
			} else if (listSong.size() == 0) {
				playlistDetail.loadingData.loadingFinish(false,
						"Playlist không có bài hát nào!");
				playlistDetail.selectSongPlayInterface = null;
			} else {
				playlistDetail.mPlaylist.songList = listSong;
				playlistDetail.loadingData.loadingFinish(true, null);
				playlistDetail.showPlaylistDetail();
			}
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			if (!checkAppIsLive()) {
				return;
			}
			PlaylistDetail albumDetail = playlistDetailRfc.get();
			albumDetail.loadingData.startLoading();
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.tv_play_all_song:
			if (selectSongPlayInterface != null) {
				selectSongPlayInterface.playAllSong();
			}
			break;
		case R.id.tv_select_song_play:
			if (selectSongPlayInterface != null) {
				selectSongPlayInterface.selectSongPlay();
			}
			break;

		default:
			break;
		}
	}

}
